package com.dcy.security.auth.exception;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.web.util.HtmlUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @Author：dcy
 * @Description: 序列化异常类
 * @Date: 2019/10/14 15:28
 */
public class UserOAuth2ExceptionSerializer extends StdSerializer<UserOAuth2Exception> {

    protected UserOAuth2ExceptionSerializer() {
        super(UserOAuth2Exception.class);
    }


    @Override
    public void serialize(UserOAuth2Exception e, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {
        generator.writeStartObject();
        generator.writeBooleanField("success", false);
        generator.writeObjectField("code", e.getHttpErrorCode());
        switch (e.getHttpErrorCode()) {
            case 400:
                generator.writeObjectField("msg", "用户名和密码错误！");
                break;
            case 401:
                generator.writeObjectField("msg", "未经授权！");
                break;
            case 403:
                generator.writeObjectField("msg", "拒绝访问！");
                break;
            case 405:
                generator.writeObjectField("msg", "不允许使用方法！");
                break;
            default:
                generator.writeObjectField("msg", "服务器错误！");
                break;
        }

        generator.writeObjectField("data", null);
        String message = e.getMessage();
        if (message != null) {
            message = HtmlUtils.htmlEscape(message);
        }
        generator.writeStringField("message", message);
        if (e.getAdditionalInformation() != null) {
            for (Map.Entry<String, String> entry : e.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                generator.writeStringField(key, add);
            }
        }
        generator.writeEndObject();
    }
}
